import 'dart:io';
import 'dart:typed_data';

import 'package:ffmpeg_kit_flutter_new/ffmpeg_kit.dart';
import 'package:path_provider/path_provider.dart';

class DecodedAudio {
  final Float32List samples;
  final int sampleRate;
  DecodedAudio(this.samples, this.sampleRate);
}

Future<DecodedAudio> decodeMp3Bytes(Uint8List bytes) async {
  final tmpDir = await getTemporaryDirectory();
  final inPath = '${tmpDir.path}/input_mp3_${DateTime.now().millisecondsSinceEpoch}.mp3';
  final outPath = '${tmpDir.path}/output_pcm_${DateTime.now().millisecondsSinceEpoch}.pcm';

  // 写入输入 MP3 文件
  final inFile = File(inPath);
  await inFile.writeAsBytes(bytes, flush: true);

  // 使用 FFmpeg 将 MP3 转为 16kHz 单声道 float32 原始 PCM（f32le）
  final cmd = '-y -i "$inPath" -ar 16000 -ac 1 -f f32le "$outPath"';
  await FFmpegKit.execute(cmd);

  // 读取输出 PCM 并转为 Float32List
  final outFile = File(outPath);
  final outBytes = await outFile.readAsBytes();
  final samples = Float32List.view(outBytes.buffer);

  // 清理临时文件
  try {
    await inFile.delete();
    await outFile.delete();
  } catch (_) {}

  return DecodedAudio(samples, 16000);
}
